package com.enhe.gck.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.enhe.gck.domain.PrintInvoiceSet;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 生成发票PDFService
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class InvoiceExportSetService {

    @SneakyThrows
    public byte[] generatePdf(PrintInvoiceSet printInvoice, byte[] inputStream) {
        PdfStamper ps = null;
        PdfReader reader = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            reader = new PdfReader(inputStream);
            byteArrayOutputStream = new ByteArrayOutputStream();
            ps = new PdfStamper(reader, byteArrayOutputStream);
            AcroFields form = ps.getAcroFields();
            BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(bfChinese);
            String gckCode = "VAT:"+printInvoice.getGckVATNO()+"/NIF:"+printInvoice.getGckNIF()+"/IDN:"+printInvoice.getGckIDN();
            form.setField("gckCode", gckCode);
            form.setField("date", printInvoice.getDate());
            form.setField("invoiceNo", printInvoice.getInvoiceNo());
            form.setField("clientVatNo", printInvoice.getClientVATNO());
            form.setField("clientIdn", printInvoice.getClientIDN());
            form.setField("clientNif", printInvoice.getClientNIF());
            form.setField("clientVat", printInvoice.getClientVAT());
            form.setField("address", printInvoice.getAddress());
            form.setField("roadNumber", printInvoice.getRoadNumber());
            form.setField("province", printInvoice.getProvince());
            form.setField("state", printInvoice.getState());
            form.setField("totalAmountEXVAT", NumberUtil.decimalFormat(",###.##", new BigDecimal(printInvoice.getTotalAmountEXVAT())));
            form.setField("avtAmount", NumberUtil.decimalFormat(",###.##", new BigDecimal(printInvoice.getAvtAmount())));
            form.setField("amountUSD", NumberUtil.decimalFormat(",###.##", new BigDecimal(printInvoice.getAmountUSD())));
            form.setField("amountCDF", NumberUtil.decimalFormat(",###.##", new BigDecimal(printInvoice.getAmountCDF())));
            form.setField("barCode", "*" + printInvoice.getInvoiceNo() + "*");
            form.setField("remark", printInvoice.getRemark());


            form.setField("cash", printInvoice.isCash()?"Yes":"");
            form.setField("credit", printInvoice.isCredit()?"Yes":"");
            form.setField("clientName", printInvoice.getClientName());

            Date currentDate = new Date();
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("EEE, d MMM yyyy h:mm:ssa", Locale.ENGLISH);
            String formattedDate1 = dateFormat1.format(currentDate);

            form.setField("salesSlip", printInvoice.getSalesSlip());
            form.setField("makeTime", formattedDate1);
            form.setField("rate", "(" + printInvoice.getRate() + "%)");

            Barcode128 barcode128 = new Barcode128();
            //条形码字号
            barcode128.setCode(printInvoice.getInvoiceNo());
            barcode128.setFont(null);
            barcode128.setSize(15); //条形码高度
            barcode128.setBarHeight(30);
            barcode128.setBaseline(15);
            barcode128.setStartStopText(false);
            barcode128.setExtended(false);
            //绘制条形码在第一页
            PdfContentByte cb = ps.getOverContent(1);
            //生成条形码图片
            Image image128 = barcode128.createImageWithBarcode(cb, null, null);
            //条形码位置
            image128.setAbsolutePosition(450, 723);
            //加入条形码
            cb.addImage(image128);
            ps.setFormFlattening(true);
            List<AcroFields.FieldPosition> table = form.getFieldPositions("table1");
            List<AcroFields.FieldPosition> table1 = form.getFieldPositions("table");
            if(table!=null&& !table.isEmpty()){
                final int size = printInvoice.getItems().size();
                Rectangle rect = table.get(0).position;
                PdfPTable pTable = new PdfPTable(7);
                Font fontZH = new Font(bfChinese, 10f, 0);
                pTable.getDefaultCell().setHorizontalAlignment(1);
                pTable.setWidthPercentage(100.0f);
                float totalWidth = rect.getRight() - rect.getLeft() - 1;
                //计算表格宽度
                float[] columnWidth = {(float) (totalWidth * 0.15), (float) (totalWidth * 0.20), (float) (totalWidth * 0.23), (float) (totalWidth * 0.11), (float) (totalWidth * 0.10), (float) (totalWidth * 0.10), (float) (totalWidth * 0.11)};
                pTable.setTotalWidth(columnWidth);
                pTable.setLockedWidth(true);
                int border = 0;
                for (PrintInvoiceSet.InvoiceItemsSet invoiceItems : printInvoice.getItems()) {
                    //border+=1;
                    pTable.addCell(generateCell(invoiceItems.getItemId(), border, fontZH));
                    pTable.addCell(generateCell(invoiceItems.getBl(), border, fontZH));
                    pTable.addCell(generateCell(invoiceItems.getDescription(), border, fontZH));
                    pTable.addCell(generateCell(invoiceItems.getQuantity(), border, fontZH));
                    pTable.addCell(generateCell(invoiceItems.getPrice(), border, fontZH));
                    pTable.addCell(generateCell(invoiceItems.getDiscountNet(), border, fontZH));
                    pTable.addCell(generateCell(invoiceItems.getAmount(), border, fontZH));
                }
                pTable.setKeepTogether(true);
                pTable.setSplitLate(false);
                pTable.setSplitRows(true);
                //每页数量
                int totalsize = 17;
                //计算需要分页的总页数
                int totalPage = size % totalsize == totalsize ? size / totalsize : size / totalsize + 1;
                if (totalPage == 1) {
                    //获table页面
                    PdfContentByte under = ps.getOverContent(1);
                    //添加table
                    pTable.writeSelectedRows(0, -1, rect.getLeft(), rect.getTop(), under);
                } else {
                    for (int i = 1; i <= totalPage; i++) {
                        PdfContentByte under = ps.getOverContent(i);
                        if (i == 1) {
                            pTable.writeSelectedRows(0, totalsize, rect.getLeft(), rect.getTop(), under);
                        } else {
                            pTable.writeSelectedRows((i - 1) * totalsize, i * totalsize, rect.getLeft(), rect.getTop(), under);
                        }
                    }
                }
            }else if (table1!=null&& !table1.isEmpty()){
                final int size = printInvoice.getItems().size();
                Rectangle rect = table1.get(0).position;
                PdfPTable pTable = new PdfPTable(5);
                Font fontZH = new Font(bfChinese, 10f, 0);
                pTable.getDefaultCell().setHorizontalAlignment(1);
                pTable.setWidthPercentage(100.0f);
                float totalWidth = rect.getRight() - rect.getLeft() - 1;
                //计算表格宽度
                float[] columnWidth = {(float) (totalWidth * 0.19),(float) (totalWidth * 0.40), (float) (totalWidth * 0.16), (float) (totalWidth * 0.14), (float) (totalWidth * 0.11)};
                pTable.setTotalWidth(columnWidth);
                pTable.setLockedWidth(true);
                int border = 0;
                for (PrintInvoiceSet.InvoiceItemsSet invoiceItems : printInvoice.getItems()) {
                    //border+=1;
                    pTable.addCell(generateCell(invoiceItems.getCode(), border, fontZH));
                    pTable.addCell(generateCell(invoiceItems.getDescription(), border, fontZH));
                    pTable.addCell(generateCell(invoiceItems.getQuantity(), border, fontZH));
                    pTable.addCell(generateCell(invoiceItems.getPrice()+"$", border, fontZH));
                    pTable.addCell(generateCell(invoiceItems.getAmount()+"$", border, fontZH));
                }
                pTable.setKeepTogether(true);
                pTable.setSplitLate(false);
                pTable.setSplitRows(true);
                //每页数量
                int totalsize = 17;
                //计算需要分页的总页数
                int totalPage = size % totalsize == totalsize ? size / totalsize : size / totalsize + 1;
                if (totalPage == 1) {
                    //获table页面
                    PdfContentByte under = ps.getOverContent(1);
                    //添加table
                    pTable.writeSelectedRows(0, -1, rect.getLeft(), rect.getTop(), under);
                } else {
                    for (int i = 1; i <= totalPage; i++) {
                        PdfContentByte under = ps.getOverContent(i);
                        if (i == 1) {
                            pTable.writeSelectedRows(0, totalsize, rect.getLeft(), rect.getTop(), under);
                        } else {
                            pTable.writeSelectedRows((i - 1) * totalsize, i * totalsize, rect.getLeft(), rect.getTop(), under);
                        }
                    }
                }
            }
            ps.close();
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ps != null) {
                    ps.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (byteArrayOutputStream != null) {
                    byteArrayOutputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private PdfPCell generateCell(String value, int border, Font fontZH) {
        PdfPCell cell = new PdfPCell(new Phrase(value, fontZH));
        cell.setBorder(border);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        return cell;
    }


}